# @Author：cnzdy
# @Email：cn_zdy@126.com
# @Time: 2021/10/5 12:48
# @File: models.py


from torch import nn
from torchsummary import summary


class AlexNet(nn.Module):
    """
        code from torchvision/models/alexnet.py
        结构参考 <https://arxiv.org/abs/1404.5997>
    """

    def __init__(self, num_classes=2):
        super(AlexNet, self).__init__()

        self.features = nn.Sequential(
            # conv1
            nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),

            nn.Conv2d(64, 192, kernel_size=5, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),

            nn.Conv2d(192, 384, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),

            nn.Conv2d(384, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),

            # conv5
            nn.Conv2d(256, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
        )
        self.classifier = nn.Sequential(
            # fc6
            nn.Linear(256 * 6 * 6, 4096),
            nn.ReLU(inplace=True),
            nn.Dropout(),

            # fc7
            nn.Linear(4096, 4096),
            nn.ReLU(inplace=True),
            nn.Dropout(),

            # fc8
            nn.Linear(4096, num_classes),
        )

    def forward(self, x):
        x = self.features(x)

        # view 相当于numpy中resize的功能，view函数只能用在内存中连续存储的张量上
        # 把原先tensor中的数据按照行优先的顺序排成一个一维的数据，然后按照参数组合成其他维度的tensor
        # x.size(0)：是batch_size
        x = x.view(x.size(0), 256 * 6 * 6)
        # print(f"x: {x.size()}")
        x = self.classifier(x)
        return x


if __name__ == '__main__':
    model = AlexNet()
    print(model)
    summary(model.cuda(), input_size=(3, 224, 224))
